/**
 * @file shell_port.c
 * @author Letter (NevermindZZT@gmail.com)
 * @brief 
 * @version 0.1
 * @date 2019-02-22
 * 
 * @Copyright (c) 2019 Unicook
 * 
 */

#include "shell.h"
#include "comm.h"
#include "usart.h"
#include "maos_task.h"
#include "maos_malloc.h"

Shell shell;
char shellBuffer[512];

static uint16_t snedPos=0;
static pCOMM comm= NULL;

static PACKDATA *packData=NULL;
static char *sendBuf=NULL;


/**
 * @brief 用户shell周期调用
 * 
 * @param data 数据
 */
void userShellLoop(void)
{
	if(!snedPos || !comm)
		return;

	memset(&packData->ack,0,sizeof(POTOCOLACK));						//初始应答参数-不需要应答
	packData->dataLen = snedPos;
	comm->send_data(comm,packData);
	snedPos = 0;

}

/**
 * @brief 用户shell写
 * 
 * @param data 数据
 */
void userShellWrite(char data)
{
	sendBuf[snedPos++]=data;
	if(snedPos>=256)
		userShellLoop();

}




unsigned long get_systick(void)
{
	return maos_tick;
}

static void analyze(void *arg,void *data,uint16_t len)
{
	if(!data || !len)
		return;
	
	char *p=(char *)data;
	while(len--)
	{
		shellHandler(&shell, *p++);
	}
}

POCOTOLFUN shell_uart=
{
	.analyze = analyze,
};

/**
 * @brief 用户shell初始化
 * 
 */
void userShellInit(void)
{
	pMALLOC_OPS var = Tmalloc.find("MALLOC_VAR");							//查找动态内存
	packData = var->malloc(256+sizeof(PACKDATA));
	sendBuf = (char *)&packData->data;

	//通讯设置
	
	COMM_INI arg={
		.driverName = "driver_rs232",
		.baud = 115200,
		.prol = &shell_uart,
		.memName = "MALLOC_VAR",
		.TDataMaxSize = 512,
	};
	comm =Tcomm.create("driver_rs232",&arg);
	
    shell.write = userShellWrite;
    shellInit(&shell, shellBuffer, 512);
	
	Task.pfn_add(userShellLoop,TASK_FREE,10);
	
	#include "version.h"
	shellPrint(&shell,"version: V%d.%d.%d  %x\r\n",
				(VERSION>>8)&0xF,(VERSION>>4)&0xF,(VERSION>>0)&0xF,
				VERSION_TIME);

}

